// pages/couple/bind.js
const app = getApp()

Page({
  // 模拟登录（开发模式专用）
  mockLogin(username, password) {
    if (!app.devConfig.enabled) return false
    const res = app.devConfig.mockMethods.login(username, password)
    if (res.success) {
      app.globalData.userInfo = res.data.userInfo
      app.globalData.token = res.data.token
      app.globalData.isLoggedIn = true
      return true
    }
    return false
  },
  data: {
    hasCouple: false,
    coupleInfo: null,
    bindCode: '',
    inputCode: '',
    isGenerating: false,
    isSubmitting: false,
    codeGeneratedAt: null,  // 绑定码生成时间
    isCodeUsed: false       // 绑定码是否已使用
  },

  onLoad() {
    this.checkCoupleStatus()
  },

  // 检查当前绑定状态（增强版）
  checkCoupleStatus() {
    if (!app || !app.globalData) {
      console.error('App实例未初始化')
      return
    }
    
    const { coupleInfo } = app.globalData
    this.setData({
      hasCouple: !!coupleInfo,
      coupleInfo: coupleInfo || null
    })
  },

  // 监听全局数据变化
  watchGlobalData() {
    if (this._globalDataWatcher) return
    
    this._globalDataWatcher = app.watchGlobalData({
      coupleInfo: (newVal) => {
        this.setData({
          hasCouple: !!newVal,
          coupleInfo: newVal || null
        })
      }
    })
  },
  
  onLoad() {
    this.watchGlobalData()
    this.checkCoupleStatus()
  },
  
  onUnload() {
    if (this._globalDataWatcher) {
      this._globalDataWatcher()
      this._globalDataWatcher = null
    }
  },

  // 生成绑定码
  generateCode() {
    this.setData({ isGenerating: true })
    
    if (app.devConfig.enabled) {
      // 开发模式：使用固定绑定码
      this.setData({
        bindCode: app.devConfig.coupleCode || '131452',
        isGenerating: false,
        codeGeneratedAt: new Date().getTime(),
        isCodeUsed: false
      })
      wx.showToast({ title: '生成绑定码成功', icon: 'success' })
    } else {
      // 生产环境：调用真实API
      const coupleService = require('../../services/couple')
      coupleService.generateCode().then(res => {
        this.setData({
          bindCode: res.data.code,
          isGenerating: false,
          codeGeneratedAt: res.data.generatedAt,
          isCodeUsed: false
        })
      }).catch(err => {
        this.setData({ isGenerating: false })
        wx.showToast({ title: '生成绑定码失败', icon: 'none' })
      })
    }
  },

  // 生成6位随机码
  generateRandomCode() {
    return Math.floor(100000 + Math.random() * 900000).toString()
  },

  // 输入绑定码
  onCodeInput(e) {
    this.setData({ inputCode: e.detail })
  },

  // 提交绑定
  submitBind() {
    const { inputCode, bindCode, codeGeneratedAt } = this.data
    
    // 验证绑定码
    if (!inputCode || inputCode.length !== 6) {
      wx.showToast({ title: '请输入6位绑定码', icon: 'none' })
      return
    }
    
    // 检查绑定码是否匹配
    if (inputCode !== bindCode) {
      wx.showToast({ title: '绑定码不匹配', icon: 'none' })
      return
    }
    
    // 检查是否已使用
    if (this.data.isCodeUsed) {
      wx.showToast({ title: '该绑定码已被使用', icon: 'none' })
      return
    }
    
    // 检查是否过期 (30分钟)
    const now = new Date().getTime()
    if (now - codeGeneratedAt > 30 * 60 * 1000) {
      wx.showToast({ title: '绑定码已过期', icon: 'none' })
      return
    }

    this.setData({ isSubmitting: true, isCodeUsed: true })
    
    if (app.devConfig.enabled) {
      // 开发模式：使用永久有效的绑定码
      const res = {
        success: inputCode === app.devConfig.mockData.coupleBinding.code,
        data: {
          partnerInfo: Object.values(app.devConfig.mockData.users).find(
            u => u.username !== app.devConfig.mockData.currentUser.username
          )
        },
        message: inputCode === app.devConfig.mockData.coupleBinding.code 
          ? "绑定成功" 
          : "绑定码错误，请使用131452"
      }
      if (res.success) {
        wx.showToast({ 
          title: '绑定成功',
          icon: 'success',
          duration: 1500
        })
        app.saveCouple({
          partnerName: res.data.partnerInfo.nickname,
          partnerAvatar: res.data.partnerInfo.avatar,
          bindDate: new Date().toISOString()
        })
        this.setData({
          hasCouple: true,
          isSubmitting: false,
          coupleInfo: app.globalData.coupleInfo
        })
        // 2秒后自动返回上一页
        setTimeout(() => {
          wx.navigateBack()
        }, 2000)
      } else {
        this.setData({ isSubmitting: false, isCodeUsed: false })
        wx.showToast({ title: res.message, icon: 'none' })
      }
    } else {
      // 生产环境：调用真实API
      const coupleService = require('../../services/couple')
      coupleService.bindCouple(inputCode).then(res => {
        wx.showToast({ 
          title: res.data.message,
          icon: 'success',
          duration: 1500
        })
        app.saveCouple(res.data)
        this.setData({
          hasCouple: true,
          isSubmitting: false,
          coupleInfo: app.globalData.coupleInfo
        })
        // 2秒后自动返回上一页
        setTimeout(() => {
          wx.navigateBack()
        }, 2000)
      }).catch(err => {
        this.setData({ isSubmitting: false, isCodeUsed: false })
        wx.showToast({ title: err.message || '绑定失败', icon: 'none' })
      })
    }
  },

  // 返回上一页
  onBack() {
    wx.navigateBack()
  },
  
  // 解除绑定关系
  unbindCouple() {
    wx.showModal({
      title: '确认解除',
      content: '确定要解除情侣关系吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({ isSubmitting: true })
          
          // 模拟API请求
          setTimeout(() => {
            app.saveCouple(null)
            this.setData({
              hasCouple: false,
              coupleInfo: null,
              isSubmitting: false
            })
            wx.showToast({ title: '已解除绑定' })
          }, 800)
        }
      }
    })
  }
})